# coding=utf-8
import hashlib
import os
import platform
import json

# 此为忽略上传的配置
ignore_dirs = ['.git']
ignore_files = ['.DS_Store']
# ------------别搞混了-------------
# 此为hash的配置
ingored_folder = [".sunjian"]
hold_file = [".md"]


class Tools:
    system = platform.system()

    @staticmethod
    def is_ignore(src):
        dirs = src.split('/')
        for p in ignore_dirs:
            for dir in dirs:
                if dir.startswith(p):
                    return True
        for p in ignore_files:
            if src.endswith(p):
                return True
        return False

    # True 则保留文件，False 则相反
    @staticmethod
    def filter_hold_file(path):
        if os.path.splitext(path)[1] not in hold_file:
            return False
        return True

    # True 则保留文件，False 则相反
    @staticmethod
    def filter_ignored_folder(path):
        for f in path.split("/"):
            if f in ingored_folder:
                return False
        return True

    @staticmethod
    def getAllFilesIngored(src):

        files = Tools.getAllFiles(src)
        files = filter(Tools.filter_hold_file, files)
        files = filter(Tools.filter_ignored_folder, files)
        return files

    @staticmethod
    def getAllFiles(src):
        file_list = []
        for root, dirs, files in os.walk(src):
            for filespath in files:
                path = os.path.join(root, filespath)
                path = path.replace(src, '')
                path = path.replace('\\', '/')
                # if not path.startswith('/'):
                #     path = '/' + path
                file_list.append(path)
        return file_list

    @staticmethod
    def cmpDelFiles(old_list, new_list):
        old = set(old_list)
        new = set(new_list)

        del_list = list(old.difference(new))
        return del_list

    @staticmethod
    def cmpAddFiles(old_list, new_list):
        old = set(old_list)
        new = set(new_list)

        del_list = list(new.difference(old))
        return del_list

    # 假定path已经添加了prefix
    @staticmethod
    def getFileInfo(src, path):
        d = {}
        print "path", path
        with open(path, "r") as f:
            while True:
                line = f.readline()
                if not line:
                    break
                if line.replace(" ", "") == "":
                    continue
                if ":" not in line:
                    break
                key = line.split(":", 1)[0].strip()
                value = line.split(":", 1)[1].strip()
                d.update(dict({key: value}))

        d.update(dict({"hash": Tools.hashContent(path)}))
        print "test", Tools.remove_prefix(src, path)
        return dict({Tools.remove_prefix(src, path): d})

    # 假定path已经添加了prefix
    @staticmethod
    def hashContent(path):
        m = hashlib.md5()
        f = open(path, "rb")
        while True:
            data = f.read(10240)
            if not data:
                break
            m.update(data)
        return m.hexdigest()

    @staticmethod
    def decode(string, encode=None):
        if isinstance(string, unicode):
            return string
        else:
            if not encode:
                if 'Darwin' in Tools.system:
                    encode = 'utf8'
                else:
                    encode = 'gbk'
            return string.decode(encode)

    @staticmethod
    def encode(string, encode=None):
        if not encode:
            if 'Darwin' in Tools.system:
                encode = 'utf8'
            else:
                encode = 'gbk'
        if isinstance(string, unicode):
            return string.encode(encode)
        else:
            return Tools.decode(string).encode(encode)

    @staticmethod
    def regularize_path(path, encode=None):
        path = Tools.decode(path, encode)
        return Tools.replace_backslash(path)

    # windows支持斜杠，程序中所有路径全部以正斜杠区分
    @staticmethod
    def replace_backslash(path):
        return path.replace('\\', '/')

    # 去除路径的前缀
    @staticmethod
    def remove_prefix(src, path):
        return path.replace(src, '')

    @staticmethod
    def add_prefix(src, path):
        # 拼接路径时，要去掉后面路径的正斜杠
        return Tools.replace_backslash(os.path.join(src, path[1:]))

    # 假定add_path_list中的所有path已经去掉prefix
    @staticmethod
    def update_add(src, add_path_list):
        p = os.path.join(src, ".sunjian")
        if not os.path.exists(p):
            os.mkdir(p)
        with open(os.path.join(p, "update.json"), "a+") as f:
            string = f.read()
        d = {}
        if string.strip():
            d = json.loads(string)
        s = set(d.get("add", ""))
        for path in add_path_list:
            s.add(path)
        d.update({"add": list(s)})
        json.dump(d, open(os.path.join(p, "update.json"), "w"))

    # 假定del_path_list中的所有path已经去掉prefix
    @staticmethod
    def update_delete(src, del_path_list):
        p = os.path.join(src, ".sunjian")
        if not os.path.exists(p):
            os.mkdir(p)
        with open(os.path.join(p, "update.json"), "a+") as f:
            string = f.read()
        d = {}
        if string.strip():
            d = json.loads(string)
        s = set(d.get("del", ""))
        for path in del_path_list:
            s.add(path)
        d.update({"del": list(s)})
        json.dump(d, open(os.path.join(p, "update.json"), "w"))

    @staticmethod
    def join_path(path, *paths):
        return Tools.replace_backslash(os.path.join(path, *paths))

        # 不再使用
        # @staticmethod
        # def pathRegual(src, path):
        #     path = path[len(src):].replace("\\", "/")
        #     return path
        #
        # @staticmethod
        # def rePathRegual(src, path):
        #     if not path.startswith(src):
        #         path = src + path.replace("\\", "/")
        #     return path
